package com.zw.blog.service.impl;

import com.zw.blog.dao.BlogRepository;
import com.zw.blog.dao.CommentRepository;
import com.zw.blog.exception.NotFoundException;
import com.zw.blog.po.Blog;
import com.zw.blog.po.Type;
import com.zw.blog.service.BlogService;
import com.zw.blog.util.MarkdownUtils;
import com.zw.blog.util.MyBeanUtils;
import com.zw.blog.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogRepository blogRepository;

    @Autowired
    private CommentRepository commentRepository;

    @Transactional
    @Override
    public Blog getBlog(Long id) {
        return blogRepository.getOne(id);
    }

    @Transactional
    @Override
    public Blog getAndConvert(Long id) {
        Blog blog = getBlog(id);
        if (blog == null) {
            throw new NotFoundException("该博客不存在");
        }
        Blog b = new Blog(); //希望原文本的markdown格式保存
        BeanUtils.copyProperties(blog, b);
        String content = b.getContent();
        String s = MarkdownUtils.markdownToHtmlExtensions(content);
        b.setContent(s);
        Integer views = blog.getViews();
        blog.setViews(views + 1);
        b.setViews(views + 1);
        return b;
    }

    /*title, type, enableRecommend三者查询*/
    @Transactional
    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (blog.getTitle() != null && blog.getTitle().length() != 0) {
                    predicates.add(cb.like(root.<String>get("title"), "%" + blog.getTitle() + "%"));
                }
                if (blog.getTagId() != null) {
                    predicates.add(cb.equal(root.join("tags").get("id"), blog.getTagId()));
                }
                if (blog.getTypeId() != null) {
                    predicates.add(cb.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
                }
                /*if (blog.isEnableRecommend()) {
                    predicates.add(cb.equal(root.<Boolean>get("enableRecommend"), true));
                } else {
                    predicates.add(cb.equal(root.<Boolean>get("enableRecommend"), false));
                }
                if (blog.isPublished()) {
                    predicates.add(cb.equal(root.<Boolean>get("published"), true));
                } else {
                    predicates.add(cb.equal(root.<Boolean>get("published"), false));
                }*/
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageable);
    }

    @Override
    public Page<Blog> listBlogPublished(Pageable pageable, BlogQuery blog) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (blog.getTypeId() != null) {
                    predicates.add(cb.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
                }
                if (blog.isEnableRecommend()) {
                    predicates.add(cb.equal(root.<Boolean>get("enableRecommend"), blog.isEnableRecommend()));
                }
                predicates.add(cb.equal(root.<Boolean>get("published"), true));
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageable);
    }

    @Override
    public Page<Blog> listBlogPublished(Pageable pageable, HttpSession session) {
        if (session.getAttribute("user") != null) {
            return blogRepository.findAllPublished(pageable);
        } else {
            return blogRepository.findAllPublishedNotPrivate(pageable);
        }
    }

    @Override
    public Page<Blog> listBlog(String query, HttpSession session, Pageable pageable) {
        if (session.getAttribute("user") != null) {
            return blogRepository.findByQuery(query, pageable);
        } else {
            return blogRepository.findByQueryNotPrivate(query, pageable);
        }
    }

    @Override
    public Page<Blog> listBlogPublished(Long tagId, HttpSession session, Pageable pageable) {
        return blogRepository.findAll(new Specification<Blog>() {
            // 关联查询？？？
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                predicates.add(cb.equal(root.join("tags").get("id"), tagId));
                predicates.add(cb.equal(root.get("published"), true));
                if (session.getAttribute("user") == null) {
                    predicates.add(cb.equal(root.get("enableRecommend"), true));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, pageable);
    }

    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "updateTime");
        Pageable pageable = PageRequest.of(0, size, sort);
        return blogRepository.findTop(pageable);
    }

    @Override
    public Map<String, List<Blog>> archiveBlog(HttpSession session) {
        List<String> years = blogRepository.findGroupYear();
        Map<String, List<Blog>> map = new HashMap<>();
        if (session.getAttribute("user") != null) {
            for (String year : years) {
                map.put(year, blogRepository.findByYear(year));
            }
        } else {
            for (String year : years) {
                map.put(year, blogRepository.findByYearNotPrivate(year));
            }
        }
        return map;
    }

    @Override
    public Long countBlog(HttpSession session) {
        return blogRepository.count(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                if (session.getAttribute("user") != null) {
                    return cb.equal(root.get("published"), true);
                } else {
                    return cb.and(new Predicate[]{cb.equal(root.get("published"), true), cb.equal(root.get("enableRecommend"), true)});
                }
            }
        });
    }

    @Transactional //开启事务
    @Override
    public Blog saveBlog(Blog blog) {
        if (blog.getId() == null) { //新增时id为空
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            blog.setViews(0);
        } else {
            blog.setUpdateTime(new Date());
        }
        return blogRepository.save(blog);
    }

    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {
        Blog b = blogRepository.findBlogById(id);

        if (b == null) {
            throw new NotFoundException("博客不存在");
        }
        BeanUtils.copyProperties(blog, b, MyBeanUtils.getNullPropertyNames(blog));
        return blogRepository.save(b);
    }

    @Transactional
    @Override
    public void deleteBlog(Long id) {
        Blog blog = blogRepository.getOne(id);
        blog.initCommentIds();
        List<Long> commentIds = blog.getCommentIds();
        if (commentIds != null) {
            for (Long commentId : commentIds) {
                commentRepository.deleteById(commentId);
            }
        }
        blogRepository.deleteById(id);
    }
}
